const fs = require('fs')
const path = require('path')
const FileStreamRotator = require('file-stream-rotator')
const morgan = require('morgan')

const logDirectory = path.join(__dirname, '../log')

function initMyGlobalEnv() {
    class NotFindIndexError extends Error {
        constructor(message) {
            super(message)
            this.name = this.constructor.name
        }
    }

    Object.assign(globalThis, { NotFindIndexError })
}

function initFileDir() {
    const dirs = [
        logDirectory,
        path.join(__dirname, '../survey-data'),
        path.join(__dirname, '../survey-data/answers-raw-data'),
        path.join(__dirname, '../survey-data/surveys-raw-data'),
    ]

    dirs.forEach(dir => {
        fs.existsSync(dir) || fs.mkdirSync(dir)
    })

    const filePath = path.join(
        __dirname,
        '../survey-data/manage-all-surveys.json'
    )

    fs.existsSync(filePath) || fs.writeFileSync(filePath, '[]')
}

function initLog(app) {
    const accessLogStream = FileStreamRotator.getStream({
        filename: path.join(logDirectory, 'access-%DATE%.log'),
        frequency: 'daily',
        verbose: false,
    })

    // setup the logger
    app.use(morgan('combined', { stream: accessLogStream }))
}

module.exports = function (app) {
    initMyGlobalEnv()
    initFileDir()
    initLog(app)
}
